package com.lz.specification.concurrent;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 通过ThreadLocal来结局SimpleDateFormat
 *
 * @author: li
 * @date: 2019/1/17
 */
@SuppressWarnings("unchecked")
public class SimpleDateFormatThreadLocal {
    private static ThreadLocal<SimpleDateFormat> inputThreadLocal = new ThreadLocal(){
        @Override
        protected Object initialValue() {
            return  new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }
    };
    private static ThreadLocal<SimpleDateFormat> outputThreadLocal = new ThreadLocal(){
        @Override
        protected Object initialValue() {
            return  new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    public static String convert(String s) {
        try {
            Date parse = inputThreadLocal.get().parse(s);
            String format = outputThreadLocal.get().format(parse);
            return format;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws InterruptedException {
        for(int i =0 ;i<50;i++){
            new Thread(()->{
                String convert = SimpleDateFormatThreadLocal.convert("2019-01-17 16:12");
                System.out.println(Thread.currentThread().getName()+" : "+convert);
            }).start();
        }
        TimeUnit.SECONDS.sleep(20);
    }
}
